package com.lovo.service.impl;

import com.lovo.dao.UserDAO;
import com.lovo.dto.UserDTO;
import com.lovo.enums.UserCodeEnum;
import com.lovo.exception.MyException;
import com.lovo.model.UserDO;
import com.lovo.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @title
 * @author: luo
 * @date: 2020/11/17 11:33
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDAO userDAO;
    @Override
    public UserDO login(UserDTO userDTO) {
        UserDO login = userDAO.login(userDTO);
        if (login == null) {
            throw new MyException(UserCodeEnum.USER_LOGIN_ERROR);
        }
        return login;

    }

    @Override
    public UserDO findById(Integer userId) {
        UserDO userDO = userDAO.getUserById(userId);
        if (userDO == null) {
            throw new MyException(UserCodeEnum.NO_DATA);
        }
        return userDO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDO userDO) {
        int i = userDAO.insertUser(userDO);
        if (i<=0){
            throw new MyException(UserCodeEnum.REGISTER_FAIL);
        }
    }

    @Override
    @Transactional(rollbackFor = MyException.class)
    public void deleteUser(Integer userId){
        int i = userDAO.deleteUser(userId);
        if (i<=0) {
            throw new MyException(UserCodeEnum.FAIL_DELETE_USER);
        }
    }

    @Override
    @Transactional(rollbackFor = MyException.class)
    public void updateUser(UserDO userDO) {
        int i = userDAO.updateUser(userDO);
        if (i<=0) {
            throw new MyException(UserCodeEnum.FAIL_UPDATE_USER);
        }
    }

    @Override
    public List<UserDO> findAll() {
        List<UserDO> userDOS = userDAO.selectAllUser();
        if (userDOS == null || userDOS.size()<=0) {
            throw new MyException(UserCodeEnum.NO_DATA);
        }
        return userDOS;
    }

    @Override
    public UserDO findByUserId(Integer userId) {
        UserDO userDO = userDAO.findById(userId);
        if (userDO == null) {
            throw new MyException(UserCodeEnum.NO_DATA);
        }
        return userDO;
    }


}
